# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


import time
import utils.pgsql.base.pgconn as pgconn
import json

"""
point management
add 
delete
modify
...
"""
_tblName = "tbl_point"

_DB_SCRIPT = """
CREATE TABLE IF NOT EXISTS {} (
                "pointId"  SERIAL PRIMARY KEY ,    
                "pointName"  VARCHAR(260) NOT NULL default '',    
                "punchWay" VARCHAR(260) NOT NULL default '',     
                "description"  VARCHAR(260) NOT NULL default '',   
                "location" JSON,          
                "locationNote" VARCHAR(260) NOT NULL default '',    
                "caseId"  INTEGER NOT NULL default 0,   
                "coverImgPath" VARCHAR(260) NOT NULL default '',    
                "playWayVideoPath" VARCHAR(260) NOT NULL default '',    
                "createTime" VARCHAR(32) NOT NULL default '',
                "updateTime" VARCHAR(32) NOT NULL default ''
                );

""".format(
    _tblName
)


class PgPoint:
    def __init__(self):
        self._pgConn = pgconn.pgMainConn

    def __del__(self):
        pass

    def createTbl(self):
        """
        create
        :return:
        """
        return self._pgConn.exec(_DB_SCRIPT)

    def addPoint(self, dic) -> str:
        dic["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if "location" in dic:
            dic["location"] = json.dumps(dic["location"])
        sql = 'INSERT INTO {} ("caseId","pointName","location","locationNote","punchWay","description","coverImgPath","playWayVideoPath","createTime") VALUES (\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\',\'{}\') RETURNING "pointId"'.format(
            _tblName,
            dic["caseId"],
            dic["pointName"],
            dic["location"],
            dic["locationNote"],
            dic["punchWay"],
            dic["description"],
            dic["coverImgPath"],
            dic["playWayVideoPath"],
            dic["createTime"],
        )
        res = pgconn.pgMainConn.exec_fetchone(sql)
        return res
    
    def add(self, dic) -> str:
        dic["createTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        sql_key = '\"' + '\", \"'.join(dic.keys()) + '\"'
        sql_val = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_val = sql_val + '\'' + dic[key] + '\','
            else:
                sql_val = sql_val + str(dic[key]) + ' ,'

        sql = f"""insert into {_tblName} ({sql_key}) values ({sql_val[:-1]}) RETURNING "{"pointId"}" """
        return self._pgConn.exec_fetchone(sql)

    def get_pointName(self, pointName, caseId) -> dict:
        sql = "select * from {} where \"pointName\" = '{}'  and  \"caseId\" = '{}'  ".format(
            _tblName, pointName, caseId
        )
        return self._pgConn.exec_fetchone(sql)

    def get_pointeditName(self, pointName, caseId, pointId) -> dict:
        sql = "select * from {} where \"pointName\" = '{}'  and  \"caseId\" = '{}' and \"pointId\" != '{}' ".format(
            _tblName, pointName, caseId, pointId
        )
        return self._pgConn.exec_fetchone(sql)

    
    def modify(self, ids, dic) -> bool:
        dic["updateTime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if "location" in dic:
            dic["location"] = json.dumps(dic["location"])

        sql_key = ''
        for key in dic:
            if type(dic[key]) is str:
                sql_key = sql_key + '\"' + key + '\"' + ' = \'' + dic[key] + '\','
            else:
                sql_key = sql_key + '\"' + key + '\"' + ' = ' + str(dic[key]) + ' ,'


        sql =  "update {} set {} where  ".format(_tblName, sql_key[:-1])  + " \"pointId\" = '{}' ".format(ids)
        return self._pgConn.exec(sql)

    
    def delete(self, ids) -> bool:
        sql = "delete from {} where \"pointId\" = '{}' ".format(_tblName, ids)
        return self._pgConn.exec(sql)

    
    def get(self, ids) -> dict:
        sql = "select * from {} where \"pointId\" = '{}' ".format(_tblName, ids)
        return self._pgConn.exec_fetchone(sql)
    
    def all(self) -> dict:
        sql = "select * from {} ".format(_tblName)
        return self._pgConn.exec_fetchall(sql)

    def allByCase(self, caseId) -> list:
        # sql = "select * from {} where \"caseId\" = \'{}\'".format(
        #     _tblName, caseId)
        sql = 'select a.*,c."caseName" from tbl_point a left join tbl_case c on a."caseId"=c."caseId" WHERE c."dataValid" !=0  and c."caseId"={}'.format(
            caseId
        )
        return self._pgConn.exec_fetchall(sql)

    def allByAdminRole1(self, adminId) -> list:
        sql = 'select a.*,c."caseId",c."caseName" from tbl_point a left join tbl_case c on a."caseId"=c."caseId" where c."dataValid" !=0  order by a."pointId" '.format(
            adminId
        )
        return self._pgConn.exec_fetchall(sql)

    def allByAdminRole2(self, operatorId) -> list:
        sql = 'select a.*,c."caseId",c."caseName" from tbl_point a left join tbl_case c on a."caseId"=c."caseId" WHERE c."dataValid" !=0  and c."operatorId"={}  order by a."pointId"'.format(
            operatorId
        )
        return self._pgConn.exec_fetchall(sql)

    def allByAdminRole3(self, caseId) -> list:
        sql = 'select a.*,c."caseId",c."caseName" from tbl_point a left join tbl_case c on a."caseId"=c."caseId" right join tbl_admin d on d."adminId" =  c."adminId" where c."dataValid" !=0  and d."caseId"={}  order by a."pointId"'.format(
            caseId
        )
        return self._pgConn.exec_fetchall(sql)
